package com.shawn.engine;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Debug;

import com.shawn.bean.TaskInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shawn on 2016/4/19.
 */
public class TaskEngine {
    public static List<TaskInfo> getTaskAllInfo(Context context){
        List<TaskInfo> list = new ArrayList<>();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager pm = context.getPackageManager();
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo:runningAppProcesses){
            TaskInfo taskInfo = new TaskInfo();
            String packageName = runningAppProcessInfo.processName;
            taskInfo.setPackageName(packageName);
            //获取进程所占的内存空间,int[] pids : 输入几个进程的pid,就会返回几个进程所占的空间
            Debug.MemoryInfo[] memoryInfos = activityManager.getProcessMemoryInfo(new int[]{runningAppProcessInfo.pid});
            int totalPss = memoryInfos[0].getTotalPss();
            long ramSize = totalPss*1024;
            taskInfo.setRamSize(ramSize);

            //获取application信息
            //packageName : 包名     flags:指定信息标签
            try {
                ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
                Drawable icon = applicationInfo.loadIcon(pm);
                taskInfo.setIcon(icon);
                String name  = applicationInfo.loadLabel(pm).toString();
                taskInfo.setName(name);
                //获取程序的所有标签信息,是否是系统程序是以标签的形式展示
                int flags = applicationInfo.flags;
                boolean isUser;
                if((applicationInfo.FLAG_SYSTEM & flags) == applicationInfo.FLAG_SYSTEM) {
                    isUser = false;
                }else {
                    isUser = true;
                }
                taskInfo.setUser(isUser);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            list.add(taskInfo);
        }
        return list;
    }
}
